package com.yu.mall.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yu.mall.constants.Constants;
import com.yu.mall.constants.UrlConstants;
import com.yu.mall.dto.AfsApplyInfoItem;
import com.yu.mall.dto.LogisticsDto;
import com.yu.mall.dto.PostSalesDto;
import com.yu.mall.dto.order.FreightDTO;
import com.yu.mall.dto.order.FreightSkuDTO;
import com.yu.mall.dto.order.OrderDTO;
import com.yu.mall.dto.order.OrderItemDTO;
import com.yu.mall.entity.Order;
import com.yu.mall.entity.OrderItem;
import com.yu.mall.entity.ProductInfo;
import com.yu.mall.exception.ServiceException;
import com.yu.mall.vo.SelectVO;
import com.yu.mall.vo.order.OrderChangeVO;
import com.yu.mall.vo.order.OrderCompleteVO;
import com.yu.mall.vo.order.OrderTuiKuanVO;
import com.yu.mall.vo.order.refundWaresInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class JDUtils {

	/** 日志 */

	private static String token = null;
	private static String url = "https://bizapi.jd.com/oauth2/access_token";
	private static String grantType = "access_token";
	private static String username = "广崎实业vop";
	private static String password = getMD5Str("jd123456");
	private static String clientId = "5UVIjR7ZQYBOfVt4fmWP";
	private static String clientSecret = "dHrwF3W4Dpreg0udePjC";
	
	private static String getSellPriceUrl = "https://bizapi.jd.com/api/price/getSellPrice";
	
	private static String getNewStockByIdUrl = "https://bizapi.jd.com/api/stock/getNewStockById";

	public static String productGetPageNumUrl = "https://bizapi.jd.com/api/product/getPageNum";

	public static String productGetSkuByPageUrl = "https://bizapi.jd.com/api/product/getSkuByPage";

	public static String productGetDetailUrl = "https://bizapi.jd.com/api/product/getDetail";

	public static String productSkuImageUrl = "https://bizapi.jd.com/api/product/skuImage";

	private static String getFreightUrl = "https://bizapi.jd.com/api/order/getFreight";

	private static String priceGetSellPriceUrl="https://bizapi.jd.com/api/price/getSellPrice";

	private static String productGetSimilarSkuUrl = "https://bizapi.jd.com/api/product/getSimilarSku";

	private static String afterSaleNewGetGoodsAttributesUrl = "https://bizapi.jd.com/api/afterSaleNew/getGoodsAttributes";

	private static String afterSaleNewCreateAfsApplyUrl = "https://bizapi.jd.com/api/afterSaleNew/createAfsApply";

	private static String afterSaleNewGetAfsOutlineUrl = "https://bizapi.jd.com/api/afterSaleNew/getAfsOutline";

	private static String afterSaleNewUpdateSendInfoUrl = "https://bizapi.jd.com/api/afterSaleNew/updateSendInfo";

	private static String afterSaleNewConfirmAfsOrderUrl = "https://bizapi.jd.com/api/afterSaleNew/confirmAfsOrder";

	private static String afterSaleNewCancelAfsApplyUrl = "https://bizapi.jd.com/api/afterSaleNew/cancelAfsApply";
	
	private static String productCheckUrl = "https://bizapi.jd.com/api/product/check";

	static{
		if (token == null) {
			flushToken();
		}
	}

	public static String getToken() {
		if (token == null) {
			flushToken();
		}
		return token;
	}

	public static synchronized String flushToken() {
		Map<String, String> params = new HashMap<String, String>(6);
//      // 固定值 access_token
		params.put("grant_type", grantType);
//      // 用户名
		params.put("username", username);
//      // 加密后的密码
		params.put("password", password);
		// 当前时间 格式yyyy-MM-dd HH:mm:ss
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timestamp = simpleDateFormat.format(System.currentTimeMillis());
		params.put("timestamp", timestamp);
//      // 对接账号
		params.put("client_id", clientId);
//      // 认证标识
		String sign = clientSecret + timestamp + clientId + username + password + grantType + clientSecret;
		System.out.println("加密前的sign=" + sign);
		sign = getMD5Str(sign).toUpperCase();
		params.put("sign", sign);
		System.out.println("加密后的sign=" + sign);
//      // 执行请求
		String rs = httpPost(url, params);
		JSONObject parseObject = JSONObject.parseObject(rs);
		if("true".equals(parseObject.getString("success"))) {
			JSONObject jsonObject = parseObject.getJSONObject("result");
			String access_token = jsonObject.getString("access_token");
			token=access_token;
			return access_token;
		}
		return null;
	}
	
	//获取商品价格
	public static JSONArray productCheck(String sku,String queryExts) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> params = new HashMap<String, String>();
		params.put("token", token);
		params.put("skuIds", sku);
		params.put("queryExts", queryExts);
		String rs = httpPost(productCheckUrl, params); 
		JSONObject parseObject = JSONObject.parseObject(rs);
		if("true".equals(parseObject.getString("success"))) {
			if("0000".equals(parseObject.getString("resultCode"))) {
				JSONArray jsonArray = parseObject.getJSONArray("result");
				return jsonArray;
			}
		}
		return null;
	}
	
	//获取商品价格
	public Map<String, Object> getSellPrice(String sku,String queryExts) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> params = new HashMap<String, String>();
		params.put("token", token);
		params.put("sku", sku);
		params.put("queryExts", queryExts);
		String rs = httpPost(getSellPriceUrl, params);
		JSONObject parseObject = JSONObject.parseObject(rs);
		if("true".equals(parseObject.getString("success"))) {
			if("0000".equals(parseObject.getString("resultCode"))) {
				JSONObject jsonObject = parseObject.getJSONObject("result");
				map.put("jsonObject", jsonObject);
			}
		}
		return map;
	}
	
	//获取商品库存
	public static Map<String, String> getNewStockById(String skuNums,String area) {
		Map<String, String> map = new HashMap<String, String>();
		Map<String, String> params = new HashMap<String, String>();
		params.put("token", token);
		params.put("skuNums","[{skuId:"+ skuNums+",num:101}]" );
		params.put("area", "17_1381_0_0");
		String rs = httpPost(getNewStockByIdUrl, params);
		JSONObject parseObject = JSONObject.parseObject(rs);
		if("true".equals(parseObject.getString("success"))) {
			if("0000".equals(parseObject.getString("resultCode"))) {
				JSONArray parseArray = parseObject.getJSONArray("result");
				for (int i = 0; i < parseArray.size(); i++) {
					String StockStateDesc = parseArray.getJSONObject(i).getString("stockStateId");
					if("33".equals(StockStateDesc)||"39".equals(StockStateDesc)||"40".equals(StockStateDesc)){
						map.put("stockStateDesc", "有货");
						return map;
					}
				}
				
			}
		}
		map.put("stockStateDesc", "无货");
		return map;
	}

	//查询商品池编号
	public static Map<String, Object> productGetPageNum(String queryExts) {
		Map<String, String> params = getDefMap();
		params.put("queryExts", queryExts);
		String rs = httpPost(productGetPageNumUrl, params);
		return getResultMap(JSONObject.parseObject(rs),true);
	}

	//查询池内商品编号
	public static Map<String, Object> productGetSkuByPage(String pageNum,int pageNo) {
		Map<String, String> params = getDefMap();
		params.put("pageNum", pageNum);
		params.put("pageNo", pageNo+"");
		String rs = httpPost(productGetSkuByPageUrl, params);
		return getResultMap(JSONObject.parseObject(rs),false);
	}

	//查询商品详情
	public static Map<String, Object> productGetDetail(String sku,String queryExts) {
		Map<String, String> params = getDefMap();
		params.put("sku", sku);
		params.put("queryExts", queryExts);
		String rs = httpPost(productGetDetailUrl, params);
		return getResultMap(JSONObject.parseObject(rs),false);
	}

	//查询商品图片
	public static Map<String, Object> productSkuImage(String sku) {
		Map<String, String> params = getDefMap();
		params.put("sku", sku);
		String rs = httpPost(productSkuImageUrl, params);
		return getResultMap(JSONObject.parseObject(rs),false);
	}

	//查询商品价格
	public static Map<String, Object> priceGetSellPrice(String sku) {
		Map<String, String> params = getDefMap();
		params.put("sku", sku);
		String rs = httpPost(priceGetSellPriceUrl, params);
		return getResultMap(JSONObject.parseObject(rs),true);
	}

	//查询商品规格
	public static Map<String, Object> productGetSimilarSku(String sku) {
		Map<String, String> params = getDefMap();
		params.put("skuId", sku);
		String rs = httpPost(productGetSimilarSkuUrl, params);
		return getResultMap(JSONObject.parseObject(rs),true);
	}

	//查询订单支持售后信息
	public static Map<String, Object> afterSaleNewGetGoodsAttributes(String orderId,List<String> wareIds) {
		Map<String, String> params = getDefMap();
		JSONObject param = new JSONObject();
		param.put("orderId", orderId);
		param.put("wareIds", wareIds);
		params.put("param",param.toJSONString());
		String rs = httpPost(afterSaleNewGetGoodsAttributesUrl, params);
		return getResultMap(JSONObject.parseObject(rs),true);
	}

	//申请售后
	public static String afterSaleNewCreateAfsApply(PostSalesDto dto) {
		Map<String, String> params = getDefMap();
		JSONObject param = new JSONObject();
		param.put("orderId", dto.getOrderId());
		param.put("thirdApplyId", dto.getThirdApplyId());
		//用户信息
		JSONObject customerInfo = new JSONObject();
		customerInfo.put("customerName",dto.getCustomerName());
		customerInfo.put("customerContactName",dto.getCustomerContactName());
		customerInfo.put("customerMobilePhone",dto.getCustomerMobilePhone());
		param.put("customerInfo", customerInfo);
		//取件信息
		JSONObject pickwareInfo = new JSONObject();
		pickwareInfo.put("pickwareType",dto.getPickwareType());
		pickwareInfo.put("pickWareProvince",dto.getPickWareProvince());
		pickwareInfo.put("pickWareCity",dto.getPickWareCity());
		pickwareInfo.put("pickWareCounty",dto.getPickWareCounty());
		pickwareInfo.put("pickWareVillage",dto.getPickWareVillage());
		pickwareInfo.put("pickWareAddress",dto.getPickWareAddress());
		param.put("pickwareInfo", pickwareInfo);
		//返件信息
		JSONObject returnWareInfo = new JSONObject();
		returnWareInfo.put("returnWareType",dto.getReturnWareType());
		returnWareInfo.put("returnWareProvince",dto.getReturnWareProvince());
		returnWareInfo.put("returnWareCity",dto.getReturnWareCity());
		returnWareInfo.put("returnWareCountry",dto.getReturnWareCountry());
		returnWareInfo.put("returnWareVillage",dto.getReturnWareVillage());
		returnWareInfo.put("returnWareAddress",dto.getReturnWareAddress());
		param.put("returnWareInfo", returnWareInfo);
		//申请信息集合
		JSONArray afsApplyInfoItemList = new JSONArray();
		for (AfsApplyInfoItem item : dto.getAfsApplyInfoItemList()) {
			JSONObject applyInfoItem = new JSONObject();
			applyInfoItem.put("customerExpect",item.getCustomerExpect());
			JSONObject wareDescInfo = new JSONObject();
			wareDescInfo.put("isNeedDetectionReport",item.getIsNeedDetectionReport());
			wareDescInfo.put("lossPreventionTagFlag",item.getLossPreventionTagFlag());
			wareDescInfo.put("isHasPackage",item.getIsHasPackage());
			wareDescInfo.put("packageDesc",item.getPackageDesc());
			wareDescInfo.put("questionDesc",item.getQuestionDesc());
			JSONObject wareDetailInfo = new JSONObject();
			wareDetailInfo.put("wareId",item.getWareId());
			wareDetailInfo.put("mainWareId",item.getMainWareId());
			wareDetailInfo.put("wareName",item.getWareName());
			wareDetailInfo.put("wareNum",item.getWareNum());
			wareDetailInfo.put("wareType",item.getWareType());
			applyInfoItem.put("wareDescInfo",wareDescInfo);
			applyInfoItem.put("wareDetailInfo",wareDetailInfo);
			afsApplyInfoItemList.add(applyInfoItem);
		}
		param.put("afsApplyInfoItemList", afsApplyInfoItemList);
		params.put("param",param.toJSONString());
		return httpPost(afterSaleNewCreateAfsApplyUrl, params);
	}

	//查询售后概要
	public static Map<String, Object> afterSaleNewGetAfsOutline(String orderId) {
		Map<String, String> params = getDefMap();
		JSONObject param = new JSONObject();
		param.put("orderId", orderId);
		params.put("param", param.toJSONString());
		String rs = httpPost(afterSaleNewGetAfsOutlineUrl, params);
		return getResultMap(JSONObject.parseObject(rs),false);
	}


	//售后填写运单信息(第三方)
	public static String afterSaleNewUpdateSendInfo(LogisticsDto dto) {
		Map<String, String> params = getDefMap();
		JSONObject param = new JSONObject();
		param.put("orderId", dto.getOrderId());
		param.put("thirdApplyId", dto.getThirdApplyId());
		param.put("waybillInfoList", dto.getWaybillInfoList());
		params.put("param", param.toJSONString());
		return httpPost(afterSaleNewUpdateSendInfoUrl, params);
	}

	//确认售后
	public static String afterSaleNewConfirmAfsOrder(String orderId, List<String> thirdApplyIds) {
		Map<String, String> params = getDefMap();
		JSONObject param = new JSONObject();
		param.put("orderId", orderId);
		param.put("thirdApplyIds", thirdApplyIds);
		params.put("param", param.toJSONString());
		return httpPost(afterSaleNewConfirmAfsOrderUrl, params);
	}

	//取消售后
	public static String afterSaleNewCancelAfsApply(String orderId, String thirdApplyId) {
		Map<String, String> params = getDefMap();
		JSONObject param = new JSONObject();
		param.put("orderId", orderId);
		param.put("thirdApplyId", thirdApplyId);
		param.put("remark", "取消");
		params.put("param", param.toJSONString());
		return httpPost(afterSaleNewCancelAfsApplyUrl, params);
	}

	public static Map<String, String> getDefMap(){
		Map<String, String> params = new HashMap<String, String>();
		params.put("token", token);
		return params;
	}

	public static Map<String, Object> getResultMap(JSONObject parseObject,boolean arrayFlag){
		Map<String, Object> map = new HashMap<String, Object>();
		if("true".equals(parseObject.getString("success"))) {
			if("0000".equals(parseObject.getString("resultCode"))) {
				if(arrayFlag){
					map.put("data", parseObject.getJSONArray("result"));
				}else{
					map.put("data", parseObject.getJSONObject("result"));
				}
			}
		}
		return map;
	}

	//查询运费
	public Map<String, Object> getFreight(String sku,String province,String city,String county,String town,String paymentType) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> params = new HashMap<String, String>();
		params.put("token", token);
		params.put("sku", sku);
		params.put("province", province);
		params.put("city", city);
		params.put("county", county);
		params.put("town", town);
		params.put("paymentType", paymentType);
		String rs = httpPost(getFreightUrl, params);
		JSONObject parseObject = JSONObject.parseObject(rs);
		if("true".equals(parseObject.getString("success"))) {
			if("0000".equals(parseObject.getString("resultCode"))) {
				JSONObject jsonObject = parseObject.getJSONObject("result");
				map.put("jsonObject", jsonObject);
			}
		}
		return map;
	}

	/**
	 * Md5加密
	 * 
	 * @param str
	 * @return
	 */
	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			log.error("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuilder md5StrBuff = new StringBuilder();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			} else {
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		}
		return md5StrBuff.toString();
	}

	/**
	 * 执行HttpPost请求
	 * 
	 * @param url    请求路径
	 * @param params 参数
	 * @return 结果
	 */
	public static String httpPost(String url, Map<String, String> params) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//设置超时时间
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(5000).setConnectionRequestTimeout(1000)
				.setSocketTimeout(5000).build();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		CloseableHttpResponse response = null;
		String result = null;
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			if (null != params && params.size() > 0) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					String key = entry.getKey();
					String value = entry.getValue();
					if (key == null || value == null) {
						continue;
					}
					NameValuePair pair = new BasicNameValuePair(key, value);
					nameValuePairs.add(pair);
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
			// 执行请求
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (null != entity) {
				result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
				log.info("执行请求完毕：" + result);
				EntityUtils.consume(entity);
			}
		} catch (IOException e) {
			log.error(e.getMessage());
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				log.error("请求通信[\" + reqURL + \"]时网络时，关闭异常,堆栈轨迹如下", e);
			}
			httpPost.releaseConnection();
		}
		return result;
	}

	public static void main(String[] args) throws Exception {
//		Map<String, Object> productCheck = JDUtils.productCheck("5452054","");
		
//		System.out.println(JSON.toJSONString(JDUtils.getNewStockById("100010016055","17_1381_0_0")));
//		System.out.println(JSON.toJSONString(JDUtils.productGetSimilarSku("100010721541")));
		JSONObject productDetail = new JSONObject();
		Map<String, Object> similarMap = JDUtils.productGetSimilarSku("100010721541");
        if (!similarMap.isEmpty()) {
            JSONArray similarJson = (JSONArray) similarMap.get("data");
            for(int i=0;i<similarJson.size();i++) {
                JSONArray saleAttrList = similarJson.getJSONObject(i).getJSONArray("saleAttrList");
                Iterator<Object> o = saleAttrList.iterator();
                while (o.hasNext()) {
                    JSONObject jo = (JSONObject) o.next();
                    String skuIds = jo.getString("skuIds").replaceAll("\\[|\\]", "");
                    if(!"100010721541".equals(skuIds)) {
                        o.remove(); //这种方式OK的
                    }
                }
            }
            productDetail.put("similarSkus", similarJson);
        }
        System.out.println(JSON.toJSONString(productDetail));
		/*System.out.println(JSON.toJSONString(JDUtils.productGetPageNum(null)));
		System.out.println(JSON.toJSONString(JDUtils.productGetSkuByPage("126",1)));
		System.out.println(JSON.toJSONString(JDUtils.productGetDetail("125842","wxintroduction")));
		System.out.println(JSON.toJSONString(JDUtils.productSkuImage("125842")));*/
		//
		/*List<SelectVO> province = getProvince();
		String provinceId = province.get(0).getId();
		List<SelectVO> city = getCity(provinceId);
		String cityId = city.get(0).getId();
		List<SelectVO> county = getCounty(cityId);
		String countyId = county.get(0).getId();
		List<SelectVO> town = getTown(countyId);
		String townId = town.get(0).getId();
		boolean b = checkArea(provinceId, cityId, countyId, townId);
		System.out.println(b);*/
		/*List<OrderChangeVO> changeMessage = getChangeMessage();
		
		for (OrderChangeVO orderChangeVO : changeMessage) {
			System.out.println(JSON.toJSON(orderChangeVO));
		}*/
//		afterSaleNewGetGoodsAttributes("1617167226384",Arrays.asList("3100365"));
//		selectJdOrder("148454216255");
//		List<OrderTuiKuanVO> message = getMessage();
//		getMessage();
		//148454216255
		
//		HashMap<String, String> map = Maps.newHashMap();
//		map.put("token",getToken());
//		map.put("pin","广崎实业vop");
//		map.put("type","1");
//		String result =  httpPost("https://bizapi.jd.com/api/price/getUnionBalance",map);
//		JSONObject jsonObject = JSON.parseObject(result);

	}

	private static boolean click(JSONObject jsonObject) throws ServiceException {
		if("3405".equals(jsonObject.getString("resultCode"))){
			return true;
		}

		if(Constants.JD_SUCCESS_CODE.equals(jsonObject.getString("success"))){
			return true;
		}
		throw new ServiceException("系统繁忙",jsonObject.getString("resultMessage"));
	}

	private static List<SelectVO> select(JSONObject jsonObject) throws ServiceException {
		if(click(jsonObject)){
			List<SelectVO> list = Lists.newArrayList();
			JSONObject vo = jsonObject.getJSONObject("result");
			if(Objects.nonNull(vo)){
				for (String key : vo.keySet()) {
					SelectVO selectVO = new SelectVO();
					selectVO.setId(vo.getString(key));
					selectVO.setName(key);
					list.add(selectVO);
				}
			}
			return list;
		}
		return null;
	}

	/**
	 * 获取省
	 * @return
	 */
	public static List<SelectVO> getProvince() throws ServiceException {
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		String result = httpPost(UrlConstants.URL_PROVINCE, map);
		JSONObject jsonObject = JSON.parseObject(result);
		return select(jsonObject);
	}

	/**
	 * 获取市
	 * @return
	 */
	public static List<SelectVO> getCity(String id) throws ServiceException {
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("id",id);
		String result = httpPost(UrlConstants.URL_CITY,map);
		JSONObject jsonObject = JSON.parseObject(result);
		return select(jsonObject);
	}

	/**
	 * 获取区
	 * @return
	 */
	public static List<SelectVO> getCounty(String id) throws ServiceException {
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("id",id);
		String result =  httpPost(UrlConstants.URL_COUNTY,map);
		JSONObject jsonObject = JSON.parseObject(result);
		return select(jsonObject);
	}

	/**
	 * 获取四级
	 * @return
	 */
	public static List<SelectVO> getTown(String id) throws ServiceException {
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("id",id);
		String result =  httpPost(UrlConstants.URL_TOWN,map);
		JSONObject jsonObject = JSON.parseObject(result);
		return select(jsonObject);
	}

	/**
	 * 检测地址有效性
	 * @param provinceId
	 * @param cityId
	 * @param countyId
	 * @param townId
	 * @return
	 * @throws ServiceException
	 */
	public static boolean checkArea(String provinceId,String cityId,String countyId,String townId) throws ServiceException {
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("provinceId",provinceId);
		map.put("cityId",cityId);
		map.put("countyId",countyId);
		map.put("townId",townId);
		String result =  httpPost(UrlConstants.URL_CHECK_AREA,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			JSONObject o = jsonObject.getJSONObject("result");
			String success = o.getString("success");
			if(Constants.JD_SUCCESS_CODE.equals(success)){
				return true;
			}
		}
		return false;
	}

	/**
	 * 查询运费
	 * @param freightDTO
	 * @return
	 * @throws ServiceException
	 */
	public static String getFreight(FreightDTO freightDTO) throws ServiceException {
	    String sku = "";
        List<FreightSkuDTO> freightSkuDTOS = freightDTO.getSku();
        if(CollectionUtils.isEmpty(freightSkuDTOS)){
            OrderDTO dto = (OrderDTO) freightDTO;
            List<OrderItemDTO> itemDTOS = dto.getOrderItems();
            sku = JSON.toJSONString(itemDTOS);
        }else {
            sku = JSON.toJSONString(freightSkuDTOS);
        }

		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("sku",sku);
		map.put("province",freightDTO.getProvinceId());
		map.put("city",freightDTO.getCityId());
		map.put("county",freightDTO.getCountyId());
		map.put("town",freightDTO.getTownId());
		map.put("paymentType","4");
		String result =  httpPost(UrlConstants.URL_FREIGHT,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			return jsonObject.getString("result");
		}
		return null;
	}

	/**
	 * 检查库存
	 * @param freightDTO
	 * @return
	 * @throws ServiceException
	 */
	public static boolean clickStock(FreightDTO freightDTO) throws ServiceException {
        OrderDTO dto = (OrderDTO) freightDTO;
		List<OrderItemDTO> sku = dto.getOrderItems();
        HashMap<Object, Object> errorMap = Maps.newHashMap();
        List< Map<String, String>> lists = new ArrayList<>();
		for (OrderItemDTO freightSkuDTO : sku) {
			Map<String, String> map2 = Maps.newHashMap();
			map2.put("skuId",freightSkuDTO.getSkuId());
			map2.put("num",freightSkuDTO.getNum().toString());
			errorMap.put(freightSkuDTO.getSkuId(),freightSkuDTO.getSkuName());
			lists.add(map2);
		}
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("skuNums",JSON.toJSONString(lists));
		map.put("area",dto.getProvinceId() + "_" + dto.getCityId() + "_" + dto.getCountyId() + "_" + dto.getTownId());
		log.info("校验库存" + JSON.toJSONString(map));
		String result =  httpPost(UrlConstants.URL_CHECK_STOCK,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			JSONArray resultJsonArray = jsonObject.getJSONArray("result");
			for (Object resultObject : resultJsonArray) {
				JSONObject json = (JSONObject) resultObject;
				String stockStateId = json.getString("stockStateId");
				//无货
				if(!"33".equals(stockStateId) && !"39".equals(stockStateId) && !"40".equals(stockStateId)){
					throw new ServiceException(errorMap.get(json.getString("skuId")) + " 商品无货");
				}
			}
		}
		return true;
	}

	/**
	 * 提交订单
	 * @param dto
	 * @return
	 * @throws ServiceException
	 */
	public static String submitOrder(Order ord,List<OrderItem> orderItems,OrderDTO dto) throws ServiceException {
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("thirdOrder",ord.getOrderNo());
		map.put("name",ord.getName());
		map.put("province",ord.getProvinceId());
		map.put("city",ord.getCityId());
		map.put("county",ord.getCountyId());
		map.put("town",ord.getTownId());
		map.put("address",ord.getAddress());
		map.put("mobile",ord.getPhone());
		map.put("email","xx");
		map.put("invoiceState",dto.getInvoiceState());
		map.put("invoiceType",dto.getInvoiceType());
		map.put("selectedInvoiceTitle",dto.getSelectedInvoiceTitle());
		map.put("invoiceContent",dto.getInvoiceContent());
		map.put("invoiceName",dto.getInvoiceName());
		map.put("invoicePhone",dto.getInvoicePhone());
		map.put("regCompanyName","1");
		map.put("regCode","1");
		map.put("paymentType","4");
		map.put("isUseBalance","1");
		map.put("submitState","0");


		List<Map<String,String>> skus = new ArrayList<>();
        for (OrderItem orderItem : orderItems) {
            HashMap<String, String> itemMap = Maps.newHashMap();
            itemMap.put("skuId",orderItem.getSkuId());
            itemMap.put("num",orderItem.getNum().toString());
            itemMap.put("price",orderItem.getPrice().toString());
            itemMap.put("bNeedGift","false");
            skus.add(itemMap);
        }
        map.put("sku", JSON.toJSONString(skus));
		String result =  httpPost(UrlConstants.URL_SUBMITORDER,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			return jsonObject.getString("result");
		}
		return null;
	}
	
	/**
	 *反查订单
	 * @return
	 * @throws ServiceException
	 */
	public static String selectJdOrderIdByThirdOrder(String orderNo) throws ServiceException {
		
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("orderNo",orderNo);
		String result =  httpPost(UrlConstants.URL_SELECTJDORDERIDBYTHIRDORDER,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			return jsonObject.getString("result");
		}
		return null;
	}

	/**
	 * 商城余额
	 * @return
	 * @throws ServiceException
	 */
	public static String getUnionBalance() throws ServiceException {
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("pin","广崎实业vop");
		map.put("type","1");
		String result =  httpPost(UrlConstants.URL_UNION_BALANCE,map);
		JSONObject jsonObject = JSON.parseObject(result);
			if(click(jsonObject)){
				return jsonObject.getString("result");
			}
		return null;
	}
	
	/**
	 *确认预占库存订单
	 * @return
	 * @throws ServiceException
	 */
	public static String confirmOrder(String jdOrderId) throws ServiceException {
		
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("jdOrderId",jdOrderId);
		String result =  httpPost(UrlConstants.URL_CONFIRMORDER,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			return jsonObject.getString("result");
		}
		return null;
	}
	
	/**
	 *取消未确认订单
	 * @param jdOrderId
	 * @return
	 * @throws ServiceException
	 */
	public static String cancel(String jdOrderId) throws ServiceException {
		
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("jdOrderId",jdOrderId);
		String result =  httpPost(UrlConstants.URL_CANCEL,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			return jsonObject.getString("result");
		}
		return null;
	}
	
	
	/**
	 *查询订单详情
	 * @param jdOrderId
	 * @return
	 * @throws ServiceException
	 */
	public static String selectJdOrder(String jdOrderId) throws ServiceException {
		
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("jdOrderId",jdOrderId);
		String result =  httpPost(UrlConstants.URL_SELECTJDORDER,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			return jsonObject.getString("result");
		}
		return null;
	}

	public static List<OrderCompleteVO> synOrderId() throws ServiceException {
		List<OrderCompleteVO> list = new ArrayList<>();
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("type","1");
		String result =  httpPost(UrlConstants.URL_MESSAGE,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if("false".equals(jsonObject.getString("success"))){
			return list;
		}
		if("true".equals(jsonObject.getString("success"))){
			JSONArray jsonArray = jsonObject.getJSONArray("result");
			if(!CollectionUtils.isEmpty(jsonArray)) {
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					OrderCompleteVO vo = new OrderCompleteVO();
					String id = object.getString("id");
					JSONObject result1 = object.getJSONObject("result");
					String orderId = result1.getString("pOrder");
					String completeTime = result1.getString("completeTime");
					vo.setId(id);
					vo.setOrderId(orderId);
					vo.setCompleteTime(completeTime);
					list.add(vo);
				}
			}
			return list;
		}
		return null;
	}

	public static List<OrderCompleteVO> getCompleteMessage() throws ServiceException {
		List<OrderCompleteVO> list = new ArrayList<>();
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("type","31");
		String result =  httpPost(UrlConstants.URL_MESSAGE,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if("false".equals(jsonObject.getString("success"))){
			return list;
		}
		if("true".equals(jsonObject.getString("success"))){
			JSONArray jsonArray = jsonObject.getJSONArray("result");
			if(!CollectionUtils.isEmpty(jsonArray)) {
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					OrderCompleteVO vo = new OrderCompleteVO();
					String id = object.getString("id");
					JSONObject result1 = object.getJSONObject("result");
					String orderId = result1.getString("orderId");
					String completeTime = result1.getString("completeTime");
					vo.setId(id);
					vo.setOrderId(orderId);
					vo.setCompleteTime(completeTime);
					list.add(vo);
				}
			}
			return list;
		}
		return null;
	}

	/**
	 * 删除已完成消息
	 * @return
	 * @throws ServiceException
	 */
	public static String deleteCompleteMessage(String id) throws ServiceException {
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("id",id);
		String result =  httpPost(UrlConstants.URL_DELETE_MESSAGE,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			return jsonObject.getString("result");
		}
		return null;
	}

	/**
	 * 物流消息
	 * @return
	 * @throws ServiceException
	 */
	public static String orderTrack(String jdOrderId) throws ServiceException {
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("jdOrderId",jdOrderId);
		map.put("waybillCode","1");
		String result =  httpPost(UrlConstants.URL_ORDER_TRACK,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if(click(jsonObject)){
			return jsonObject.getString("result");
		}
		return null;
	}
	
	/**
	 * 查询退款完成信息
	 * @return
	 * @throws ServiceException
	 */
	public static List<OrderTuiKuanVO> getMessage() throws ServiceException {
		List<OrderTuiKuanVO> list = new ArrayList<>();
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("type","119");
		String result =  httpPost(UrlConstants.URL_MESSAGE,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if("false".equals(jsonObject.getString("success"))){
			return list;
		}
		if("true".equals(jsonObject.getString("success"))){
			JSONArray jsonArray = jsonObject.getJSONArray("result");
			if(!CollectionUtils.isEmpty(jsonArray)) {
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					OrderTuiKuanVO vo = new OrderTuiKuanVO();
					String id = object.getString("id");
					JSONObject result1 = object.getJSONObject("result");
					String orderId = result1.getString("originalOrderId");
					String outApplyId = result1.getString("outApplyId");
					String refundAmount = result1.getString("refundAmount");
					String kaApplyId = result1.getString("kaApplyId");
					List<refundWaresInfoVO> parseArray = JSONObject.parseArray(result1.getString("refundWaresInfos"), refundWaresInfoVO.class);
					vo.setId(id);
					vo.setOrderId(orderId);
					vo.setOutApplyId(outApplyId);
					vo.setRefundAmount(refundAmount);
					vo.setRefundWaresInfos(parseArray);
					vo.setKaApplyId(kaApplyId);
					list.add(vo);
				}
			}
			return list;
		}
		return null;
	}
	
	/**
	 * 查询申请单环节变更
	 * @return
	 * @throws ServiceException
	 * @throws Exception 
	 */
	public static List<OrderChangeVO> getChangeMessage() throws ServiceException, Exception {
		List<OrderChangeVO> list = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		HashMap<String, String> map = Maps.newHashMap();
		map.put("token",getToken());
		map.put("type","104");
		String result =  httpPost(UrlConstants.URL_MESSAGE,map);
		JSONObject jsonObject = JSON.parseObject(result);
		if("false".equals(jsonObject.getString("success"))){
			return null;
		}
		if("true".equals(jsonObject.getString("success"))){
			JSONArray jsonArray = jsonObject.getJSONArray("result");
			if(!CollectionUtils.isEmpty(jsonArray)) {
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					OrderChangeVO vo = new OrderChangeVO();
					String id = object.getString("id");
					JSONObject result1 = object.getJSONObject("result");
					vo.setId(id);
					vo.setExpectationChanged(result1.getString("expectationChanged"));
					vo.setThirdApplyId(result1.getString("thirdApplyId"));
					vo.setPin(result1.getString("pin"));
					vo.setStepPassType(result1.getString("stepPassType"));
					vo.setIsOffline(result1.getString("isOffline"));
					vo.setApplyStep(result1.getString("applyStep"));
					vo.setContractNumber(result1.getString("contractNumber"));
					vo.setOrderId(result1.getString("orderId"));
					vo.setTime(sdf.parse(object.getString("time")));
					list.add(vo);
				}
			}
			list.sort(Comparator.comparing(OrderChangeVO::getTime));
			return list;
		}
		return null;
	}
}
